﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WikiQuizz.Common.Interfaces;
using WikiQuizz.Common.Entities;
using WikiQuizz.Common.Utils;
using WikiQuizz.Common.Resource;
using System.Xml.Linq;
using WikiQuizz.Common.WikiAPIHelper;
using System.Threading;

namespace WikiQuizz.StandardImplementations
{
    public class UpdateManager: IUpdateManager
    {
        ICountryManager manager;
        UpdateConfigurationEntity updateConfig;

        public UpdateManager()
        {
            updateConfig = Workbench.DeSerializeFromFile<UpdateConfigurationEntity>(Strings.UPDATE_FILE);
        }

        public void GeneralUpdate()
        {
            throw new NotImplementedException();
        }

        public void UpdateItem(int itemId)
        {
            manager = new CountryManager();

            ICollection<CountryEntity> countries = manager.Countries;

            UpdateItem(itemId, countries);

            manager.Countries = countries;
        }

        private void UpdateItem(int itemId, ICollection<CountryEntity> countries)
        {
            CountryEntity country = (from o in countries where o.PageId == itemId select o).FirstOrDefault();


            if (DateTime.Now.Subtract(country.LastUpdate) >= new TimeSpan(updateConfig.DaysUntilNextUpdate,0,0,0))
            {
                var idList = (from o in countries where o.PageId == itemId select o.PageId).Distinct<int>().ToList();
                XElement infos = WikiAPIHelperClass.QueryInfo(idList);

                int lastRev =
                    (from o in infos.Descendants(XName.Get("page")) select Convert.ToInt32(o.Attribute("lastrevid").Value)).FirstOrDefault<int>();


                if (lastRev != country.LastRevId)
                {
                    var entity = WikiAPIHelperClass.GetCountryData(country.Title);

                    country.Capital = manager.GetCapital(entity);
                    country.Population = manager.GetPopulation(entity);
                    country.PopulationDensity = manager.GetPopulationDensity(entity);
                    country.Area = manager.GetArea(entity);
                    country.OfficialLanguage = manager.GetOfficialLanguage(entity);
                    country.ISO3166 = manager.GetISO3166(entity);
                    country.LastRevId = lastRev;
                    country.LastUpdate = DateTime.Now;
                    Thread.Sleep(1000);
                } 
            }

        }
    }
}
